package cn.itcast.bos.web.action.repoint;

import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.take_delivery.WayBillService;
import cn.itcast.bos.utils.FileUtils;
import cn.itcast.bos.web.action.common.BaseAction;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;

@SuppressWarnings("serial")
@Namespace("/")
@ParentPackage("struts-default")
@Controller
@Scope("prototype")
public class RepointAction extends BaseAction<WayBill>{
	
	@Autowired
	private WayBillService wayBillService;
	@Autowired
	private DataSource dataSource;
	/**
	 * 利用poi技术生成.xls文件
	 * @return
	 */
	@Action(value="repoint_wayBill")
	public String exportFile(){
		//首先通过业务层查询到要导出的数据
		List<WayBill> wayBills = wayBillService.exportFile(model);
		//生成excel数据表
		HSSFWorkbook book = new HSSFWorkbook();
		HSSFSheet sheet = book.createSheet("运单表");
		//表头信息
		HSSFRow row = sheet.createRow(0);
		row.createCell(0).setCellValue("运单编号");
		row.createCell(1).setCellValue("寄件人");
		row.createCell(2).setCellValue("寄件人地址");
		row.createCell(3).setCellValue("寄件人电话");
		row.createCell(4).setCellValue("收货人");
		row.createCell(5).setCellValue("收货人地址");
		row.createCell(6).setCellValue("收货人电话");
		//插入数据
		for(WayBill wayBill : wayBills){
			HSSFRow persistRow = sheet.createRow(sheet.getLastRowNum() + 1);
			persistRow.createCell(0).setCellValue(wayBill.getWayBillNum());
			persistRow.createCell(1).setCellValue(wayBill.getSendName());
			persistRow.createCell(2).setCellValue(wayBill.getSendAddress());
			persistRow.createCell(3).setCellValue(wayBill.getSendMobile());
			persistRow.createCell(4).setCellValue(wayBill.getRecName());
			persistRow.createCell(5).setCellValue(wayBill.getRecAddress());
			persistRow.createCell(6).setCellValue(wayBill.getRecMobile());
		}
		try {
			//写出
			System.out.println(sheet.getRow(sheet.getLastRowNum()).getCell(0).getStringCellValue());
			ServletActionContext.getResponse().setContentType("application/vnd.ms-excel");
		    //ServletActionContext.getResponse().setContentType("text/xml;charset=utf-8");
			//获得用户浏览器类型
			String agent = ServletActionContext.getRequest().getHeader("user-agent");
			//利用工具对文件名编码
			String fileName = FileUtils.encodeDownloadFilename("运单数据表.xls", agent);
			ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+fileName);
			
			book.write(ServletActionContext.getResponse().getOutputStream());
			book.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
	
	/**
	 * 利用iText生成pdf文件
	 * @return
	 * @throws Exception 
	 * @throws DocumentException 
	 */
	@Action(value="exportpdf_wayBill")
	public String exportByPdf() throws Exception{
		//首先通过业务层查询到要导出的数据
		List<WayBill> wayBills = wayBillService.exportFile(model);
		ServletActionContext.getResponse().setContentType("application/pdf");
		//获得用户浏览器类型
		String agent = ServletActionContext.getRequest().getHeader("user-agent");
		//利用工具对文件名编码
		String fileName = FileUtils.encodeDownloadFilename("运单数据表.pdf", agent);
		ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+fileName);
		//1、创建一个文档
		Document document = new com.lowagie.text.Document();
		//2、创建一个pdfwriter实体类
		PdfWriter.getInstance(document, ServletActionContext.getResponse().getOutputStream());
		//3、打开文档
		document.open();
		// 向document 生成pdf表格满7格后自动换行
		Table table = new Table(7);
		table.setWidth(80); // 宽度
		table.setBorder(1); // 边框
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式
		table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式

		// 设置表格字体
		BaseFont cn = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
		Font font = new Font(cn, 10, Font.NORMAL, Color.BLUE);

		// 4、向表格写数据
		table.addCell(buildCell("运单编号", font));
		table.addCell(buildCell("寄件人姓名", font));
		table.addCell(buildCell("寄件人地址", font));
		table.addCell(buildCell("寄件人电话", font));
		table.addCell(buildCell("收件人姓名", font));
		table.addCell(buildCell("收件人地址", font));
		table.addCell(buildCell("收件人电话", font));
		
		// 表格数据
		for (WayBill wayBill : wayBills) {
			table.addCell(buildCell(wayBill.getWayBillNum(), font));
			table.addCell(buildCell(wayBill.getSendName(), font));
			table.addCell(buildCell(wayBill.getSendAddress(), font));
			table.addCell(buildCell(wayBill.getSendMobile(), font));
			table.addCell(buildCell(wayBill.getRecName(), font));
			table.addCell(buildCell(wayBill.getRecAddress(), font));
			table.addCell(buildCell(wayBill.getRecMobile(), font));
		}
		// 向文档添加表格
		document.add(table);
		//5、关闭
		document.close();
		return NONE;
	}
	
	
	private Cell buildCell(String content, Font font) throws BadElementException {
		Phrase phrase = new Phrase(content, font);
		return new Cell(phrase);
	}
	
	/**
	 * 利用ireport模板生成数据
	 * @throws Exception 
	 */
	@Action(value="jasperReport_wayBill")
	public String jasperReport() throws Exception{
		//首先通过业务层查询到要导出的数据
		List<WayBill> wayBills = wayBillService.exportFile(model);
		// 读取 jrxml 文件
		String jrxml = ServletActionContext.getServletContext().getRealPath("ireport/report2.jrxml");
		// 准备需要数据
		Map<String, Object> parameters = new HashMap<String, Object>();
		// 准备需要数据
		JasperReport report = JasperCompileManager.compileReport(jrxml);
		//JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, dataSource.getConnection());
		
		JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters,
				new JRBeanCollectionDataSource(wayBills));
		HttpServletResponse response = ServletActionContext.getResponse();
		OutputStream ouputStream = response.getOutputStream();
		// 设置相应参数，以附件形式保存PDF
		response.setContentType("application/pdf");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.encodeDownloadFilename("运单.pdf",
				ServletActionContext.getRequest().getHeader("user-agent")));
		// 使用JRPdfExproter导出器导出pdf
		JRPdfExporter exporter = new JRPdfExporter();
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
		exporter.exportReport();// 导出
		ouputStream.close();// 关闭流
		return NONE;
	}

}
